<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="logo">
        <img src="@/assets/image.png" alt="logo" style="height: 40px; width: 90px;">
      </div>
      
      <el-tabs v-model="activeTab" stretch>
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="密码" 
                prefix-icon="Lock"
              >
                <template #suffix>
                  <el-icon @click="showPassword = !showPassword" style="cursor: pointer">
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="rules" ref="registerFormRef">
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="用户名" prefix-icon="User"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="registerForm.password" 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="密码" 
                prefix-icon="Lock"
              >
                <template #suffix>
                  <el-icon @click="showPassword = !showPassword" style="cursor: pointer">
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input 
                v-model="registerForm.confirmPassword" 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="确认密码" 
                prefix-icon="Lock"
              >
                <template #suffix>
                  <el-icon @click="showPassword = !showPassword" style="cursor: pointer">
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRegister" style="width: 100%">注册</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { View, Hide } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import API from '@/api/index.js'

export default {
  setup() {
    const router = useRouter()
    const activeTab = ref('login')
    const loginFormRef = ref(null)
    const registerFormRef = ref(null)
    
    const loginForm = ref({
      username: '',
      password: ''
    })
    
    const registerForm = ref({
      username: '',
      password: '',
      confirmPassword: ''
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== registerForm.value.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        await loginFormRef.value.validate()
        
        const response = await API.post('/user/login', {
          username: loginForm.value.username,
          password: loginForm.value.password
        })
        
        if (response.data.code === 200) {
          const userData = response.data.data
          
          // 存储用户信息（不包含密码）
          localStorage.setItem('user', JSON.stringify(userData))
          
          // 如果勾选了记住密码，保存到localStorage
          if (rememberMe.value) {
            localStorage.setItem('rememberedCredentials', JSON.stringify({
              username: loginForm.value.username,
              password: loginForm.value.password
            }))
          } else {
            // 不记住密码时清除保存的凭证
            localStorage.removeItem('rememberedCredentials')
          }
          
          ElMessage.success('登录成功')
          // 触发全局事件，通知Header组件更新
          window.dispatchEvent(new CustomEvent('userLoginStatusChanged'))
          router.push('/').then(() => {
            location.reload();
          });
        } else {
          ElMessage.error(response.data.msg || '登录失败')
        }
      } catch (error) {
        console.error('登录失败:', error)
        if (error.response?.data?.msg) {
          ElMessage.error(error.response.data.msg)
        } else {
          ElMessage.error('登录失败，请检查网络连接')
        }
      }
    }
    
    const handleRegister = async () => {
      if (!registerFormRef.value) return
      
      try {
        await registerFormRef.value.validate()
        
        const response = await API.post('/user/register', {
          username: registerForm.value.username,
          password: registerForm.value.password
        })
        
        if (response.data.code === 200) {
          ElMessage.success('注册成功，请登录')
          activeTab.value = 'login'
          // 清空注册表单
          registerForm.value = {
            username: '',
            password: '',
            confirmPassword: ''
          }
        } else {
          ElMessage.error(response.data.msg || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        if (error.response?.data?.msg) {
          ElMessage.error(error.response.data.msg)
        } else {
          ElMessage.error('注册失败，请检查网络连接')
        }
      }
    }
    
    const showPassword = ref(false) // 控制密码显示状态
    const rememberMe = ref(false) // 记住密码状态
    
    onMounted(() => {
      const remembered = localStorage.getItem('rememberedCredentials')
      if (remembered) {
        const credentials = JSON.parse(remembered)
        loginForm.value.username = credentials.username
        loginForm.value.password = credentials.password
        rememberMe.value = true
      }
    })
    
    return {
      activeTab,
      loginForm,
      registerForm,
      loginFormRef,
      registerFormRef,
      rules,
      handleLogin,
      handleRegister,
      showPassword,
      rememberMe
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.logo h2 {
  margin-top: 10px;
  color: var(--el-color-primary);
}
</style>
